import { useEffect } from 'react';
import { history, connect } from 'umi';
import { Table, Button, Form, Select, Input, Row, Col, TreeSelect, Modal, Steps, message, Badge, List, Tag, Alert, Popover } from 'antd';
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect'
import UserBrief from '@/components/UserBrief'
import { GenderIcon } from '@/components/UserBrief'
import styles from './style.less'
import { useState } from 'react';
import { routeDictConfig } from '@/config/config';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { getContextPath } from '@/utils/utils'
import TextButton from '@/components/TextButton'
import { deleteEnterpriseUser, updateEnterpriseUser, inviteUserByUsername, confirm, confirmReject, listEnterpriseUser,getInviteLink } from '@/services/enterprise'

const { Step } = Steps;
const { TextArea } = Input;

const baseColumns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: '6%',
        render: (text, record, index) => index + 1,
    },
    {
        title: '头像昵称',
        dataIndex: 'nickName',
        key: 'nickName',
        render: (text, record) => (<UserBrief user={record.user}></UserBrief>),
    },
    {
        title: '角色',
        dataIndex: 'enterpriseRoleName',
        key: 'enterpriseRoleName',
    },
    {
        title: '部门',
        dataIndex: 'enterpriseDepartmentName',
        key: 'enterpriseDepartmentName',
    },
    {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
        render: (text, record) => record.user.email
    },
    {
        title: '性别',
        dataIndex: 'gender',
        width: '8%',
        key: 'gender',
        render: (text, record) => (<GenderIcon gender={record.user.gender}></GenderIcon>)
    },
    {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        render: (text, record) => record.user.phone
    }
];


const EnterpriseUser = (props) => {
    const {
        dispatch,
        enterpriseId,
        loadingEnterpriseUser,
        enterpriseUserList,
        enterpriseRoleList = [],
        enterpriseDepartment = [],
    
    } = props;

    const [queryForm] = Form.useForm();
    const [form] = Form.useForm();
    const [addUserModalVisible, setAddUserModalVisible] = useState(false);
    const [inviteByLinkModalVisibal, setInviteByLinkModalVisibal] = useState(false);
    const [inviteUserModalVisibal, setInviteUserModalVisibal] = useState(false);
    const [preConfirmModalVisibal, setPreConfirmModalVisibal] = useState(false);
    const [inviteUsernames, setInviteUsernames] = useState();
    const [initUserData, setInitUserData] = useState({});
    const [inviteLinkText, setInviteLinkText] = useState()
    const [copyInviteLinkText, setCopyInviteLinkText] = useState();
    const [saveUserLoading, setSaveUserLoading] = useState();
    const [inviteLinkData,setInviteLinkData] = useState()

    const [preConfirmUserList, setPreConfirmUserList] = useState()
    const queryEnterpriseUser = () => {
        dispatch({
            type: 'enterprise/listEnterpriseUser',
        })

        listEnterpriseUser({
            status: 3
        }).then(({ data }) => {
            setPreConfirmUserList(data)
        })
    }

    const deleteUser = (record) => {
        deleteEnterpriseUser({
            userId: record.userId
        }).then(({ success }) => {
            if (success) {
                message.success("删除成功");
                dispatch({
                    type: 'enterprise/listEnterpriseUser',
                })
            }
        })
    }

    useEffect(() => {
        if (dispatch) {
            queryEnterpriseUser();
            dispatch({
                type: 'enterprise/listEnterpriseRole',
            })
            dispatch({
                type: 'enterprise/getEnterpriseDepartment',
            })
        }
    }, [])

    const actionColumns = [{
        title: '操作',
        key: 'action',
        width: "10%",
        render: (text, record) => (
            <div className={styles.actionClass}>
                <TextButton onClick={() => {
                    setAddUserModalVisible(true);
                    setInitUserData(record)
                }}>修改</TextButton>
                <TextButton type="danger" onClick={() => {
                    deleteUser(record)
                }}>删除</TextButton>
            </div>
        )
    }]
    const filterColumns = (baseColumns) => {
        return [...baseColumns, ...actionColumns]
    }

    useEffect(() => {
        if (inviteLinkData) {
            let linkRoute = routeDictConfig.inviteUserRoute
            let linkUrl = getContextPath() + linkRoute + "?inviteCode=" + inviteLinkData.inviteCode;
            let inviteLinkText = inviteLinkData.text.replace("{linkUrl}", `<a href=${linkUrl}>${linkUrl}</a>`)
                .replaceAll("\n", "<br/>")
            setInviteLinkText(inviteLinkText)
            setCopyInviteLinkText(inviteLinkData.text.replace("{linkUrl}", linkUrl))
        }
    }, [inviteLinkData])

    const onQuery = (values) => {
        console.log(values)
        dispatch({
            type: 'enterprise/listEnterpriseUser',
            payload: {
                params: values
            }
        })
    }

    const confirmUser = (user) => {
        console.log(user)
        Modal.confirm({
            title: '确认同意',
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                confirm({
                    userId: user.userId
                }).then((success) => {
                    if (success) {
                        queryEnterpriseUser();
                    }
                })
                return Promise.resolve()
            }
        });
    }

    const removePreConfirmUser = (user) => {
        Modal.confirm({
            title: '确认拒绝',
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                setSaveUserLoading(true)
                confirmReject({
                    userId: user.userId
                }).then((success) => {
                    setSaveUserLoading(false)
                    if (success) {
                        queryEnterpriseUser();
                    }
                })
                return Promise.resolve()
            }
        });
    }

    const inviteByLink = async () => {
        let values = await form.validateFields();
        console.log(values)
        setInviteByLinkModalVisibal(true)
        getInviteLink({
            enterpriseId,
            ...values
        }).then(({data}) => {
            setInviteLinkData(data)
        })
    }

    const inviteWithUsername = async () => {
        let values = await form.validateFields();
        setInviteUserModalVisibal(true)
    }

    const confirmInviteUser = async () => {
        console.log(inviteUsernames);
        let values = await form.validateFields();
        Modal.confirm({
            title: '确认邀请',
            content: (<div>
                {inviteUsernames.map((username, index) => {
                    return <Tag key={index}>{username}</Tag>
                })}
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                inviteUserByUsername({
                    usernameList: inviteUsernames,
                    enterpriseDepartmentId: values.enterpriseDepartmentId,
                    enterpriseRoleId: values.enterpriseRoleId
                }).then((success) => {
                    if (success) {
                        message.success("邀请成功")
                    }
                })
                return Promise.resolve()
            }
        });
    }

    const updateUser = async () => {
        let values = await form.validateFields();
        console.log(values);
        updateEnterpriseUser(values.userId, values).then(({ success }) => {
            if (success) {
                message.success("保存成功");
                hideAddUserModal()
                dispatch({
                    type: 'enterprise/listEnterpriseUser',
                })
            }
        })
    }

    const hideAddUserModal = async () => {
        await setInitUserData({})
        form.resetFields();
        setAddUserModalVisible(false);
    };

    const addUserModalFooter = (
        <>
            {initUserData.id ? (
                <>
                    <Button type="primary" onClick={updateUser}>
                        保存
                    </Button>
                </>
            ) : (
                    <>
                        <Button type="primary" onClick={inviteByLink}>
                            生成邀请连接
                        </Button>
                        <Button type="primary" onClick={inviteWithUsername}>
                            通过用户名邀请
                        </Button>
                    </>
                )}
        </>
    );

    const mapsubDepartment = (item) => (item.subDepartment && item.subDepartment.map(sub => (
        <TreeSelect.TreeNode value={sub.id} title={sub.name} key={sub.id}>
            {mapsubDepartment(sub)}
        </TreeSelect.TreeNode>
    )));


    return (<>
        <div className={styles.userTableAction}>
            <Form
                name="query"
                form={queryForm}
                onFinish={onQuery}
            >
                <Row gutter={16} align="center">
                    <Col span={8}>
                        <Form.Item
                            label="部门"
                            name="inEnterpriseDepartmentId">
                            <TreeSelect placeholder="请选择部门"
                                allowClear
                                multiple
                                treeDefaultExpandAll>
                                {enterpriseDepartment.length > 0 && enterpriseDepartment.map((item) => (
                                    <TreeSelect.TreeNode value={item.id} title={item.name} key={item.id}>
                                        {mapsubDepartment(item)}
                                    </TreeSelect.TreeNode>
                                ))}
                            </TreeSelect>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            label="角色"
                            name="inEnterpriseRoleId">
                            <Select placeholder="请选择角色" allowClear mode="multiple" >
                                {enterpriseRoleList.map((item) => (
                                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            label="用户"
                            name="inUserId">
                            <EnterpriseUserSelect ismultiple={true} enterpriseId={enterpriseId} />
                        </Form.Item>
                    </Col>
                </Row>
                <Form.Item >
                    <div className={styles.userActionClass}>
                        <Button size="middle" type="primary" htmlType="submit" >查询</Button>
                        <Button size="middle" onClick={() => {
                            setAddUserModalVisible(true)
                        }} >新增用户</Button>
                        {preConfirmUserList && preConfirmUserList.length > 0 &&
                            <Badge count={preConfirmUserList.length}>
                                <Button size="middle" type="primary" onClick={() => {
                                    setPreConfirmModalVisibal(true)
                                }} >待确认</Button>
                            </Badge>
                        }
                    </div>
                </Form.Item>
            </Form>
        </div>
        <Table bordered
            loading={loadingEnterpriseUser || !enterpriseUserList}
            pagination={false}
            rowKey='id'
            dataSource={enterpriseUserList}
            columns={filterColumns(baseColumns)} />
        <Modal
            visible={addUserModalVisible}
            closable
            title={initUserData.id ? "修改成员" : "新增成员"}
            onCancel={() => {
                hideAddUserModal()
            }}
            footer={addUserModalFooter}
            destroyOnClose
            onOk={false}
        >
            <Form
                form={form}
                initialValues={initUserData}
            >
                {initUserData.id && (
                    <div style={{ margin: "16px" }}>
                        <UserBrief user={initUserData.user}>
                        </UserBrief>
                    </div>
                )}
                <Form.Item
                    label="用户id"
                    name="userId"
                    hidden={true}
                >
                </Form.Item>
                <Form.Item
                    label="部门"
                    name="enterpriseDepartmentId"
                    rules={[
                        {
                            required: true,
                            message: "请填入部门",
                        },
                    ]}
                >
                    <TreeSelect placeholder="请选择部门"
                        treeDefaultExpandAll
                        onSelect={(value) => {
                            form.setFieldsValue({
                                parentId: value
                            })
                        }}>
                        {enterpriseDepartment.map((item) => (
                            <TreeSelect.TreeNode value={item.id} title={item.name} key={item.id}>
                                {mapsubDepartment(item)}
                            </TreeSelect.TreeNode>
                        ))}
                    </TreeSelect>

                </Form.Item>
                <Form.Item
                    label="角色"
                    name="enterpriseRoleId"
                    rules={[
                        {
                            required: true,
                            message: "请填入部门",
                        },
                    ]}>
                    <Select placeholder="请选择角色"  >
                        {enterpriseRoleList.map((item) => (
                            <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
        <Modal
            visible={inviteByLinkModalVisibal}
            closable
            title={"邀请成员"}
            onCancel={() => {
                setInviteByLinkModalVisibal(false);
            }}
            footer={(
                <>
                    <CopyToClipboard
                        text={copyInviteLinkText}
                        onCopy={() => {
                            message.success("复制成功")
                        }}>
                        <Button>
                            复制邀请信息
                        </Button>
                    </CopyToClipboard>
                </>
            )}
            destroyOnClose
        >
            <div dangerouslySetInnerHTML={{ __html: inviteLinkText }}>
            </div>
        </Modal>
        <Modal
            visible={inviteUserModalVisibal}
            closable
            title={"邀请成员"}
            onCancel={() => {
                setInviteUserModalVisibal(false);
            }}
            width="60%"
            okButtonProps={{
                loading: saveUserLoading
            }}
            onOk={confirmInviteUser}
        >
            <Alert
                description={(
                    <>
                        1.输入用户名，用英文逗号隔开！<br />
                        2.一次最多不能超过10个！<br />
                        3.请不要包含特殊符号或换行符。<br />
                        4.发出邀请后对方同意即可加入企业。<br />
                        5.发出邀请后对方同意即可加入企业。
                    </>
                )}
                type="info"
                showIcon
            />
            <br />
            <Select mode="tags"
                style={{ width: '100%' }}
                onChange={(value) => {
                    setInviteUsernames(value);
                }}
                open={false}
                tokenSeparators={[',']}>
            </Select>
        </Modal>
        <Modal
            visible={preConfirmModalVisibal}
            closable
            title={"邀请成员"}
            onCancel={() => {
                setPreConfirmModalVisibal(false);
            }}
            footer={null}
        >
            <List dataSource={preConfirmUserList}
                renderItem={user => (
                    <List.Item
                        actions={[<Button size="small" type="primary" key="agree" onClick={() => { confirmUser(user) }}>同意</Button>,
                        <Button size="small" danger key="ingore" onClick={() => { removePreConfirmUser(user) }}>拒绝</Button>]}
                    >
                        <UserBrief user={user.user} role={user.enterpriseRoleName}></UserBrief>
                        <List.Item.Meta
                            title={user.enterpriseDepartmentName}
                        />
                    </List.Item>
                )}
            >
            </List>
        </Modal>
    </>)
}

const mappedToStates = ({ enterprise, enterpriseManage, loading }) => {
    return {
        loadingEnterpriseUser: loading.effects['enterprise/listEnterpriseUser'],
        enterpriseUserList: enterprise.enterpriseUser,
        enterpriseRoleList: enterprise.enterpriseRoleList,
        enterpriseDepartment: [enterprise.enterpriseDepartment],
    }
}


export default connect(mappedToStates)(EnterpriseUser);